<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends Vip_Controller {

    private $uid;
	function __construct ()
	{
		parent::__construct();
        $this->load->library('pagination');
		$this->load->library('form_validation');
        $this->load->model('member_m');
        $this->load->model('moneysale_m');
        $this->load->model('moneystage_m');
        $this->load->model('order_m');
        $this->uid = $this->session->userdata('user_id');
	}
	
	public function index($page=1)
	{

        $data["logs"] = [];
		$this->load->view('index', $data);
	}

	public function member(){

	    if($_POST){
            $post = $this->input->post();
            $admin = array(
                'user_company' =>$post['user_company'],
            );
            $salt =get_salt();
            $getpassword= $this->input->post('user_password',true);
            $username = isset($post['user_name']) ? htmlspecialchars($post['user_name'], ENT_QUOTES) : '';
            if(!empty($getpassword)){
                $admin['user_salt'] = $salt;
                $admin['user_password'] = password_dohash($getpassword,$salt);
            }
            if(!empty($username)){
                $admin['user_name'] = $username;
                $admin['user_uname'] = $username;
            }
            $res = $this->user_m->update_user($this->uid,$admin);
            if($res){
                echo json_encode(array('status' => 200,"msg"=>"修改成功"));
                exit();
            }else{
                echo json_encode(array('status' => 400,"msg"=>"修改失败"));
                exit();
            }
        }
        $data["logs"] = [];
        $this->load->view('member', $data);
    }

    public function address(){


	    if($_POST){
            $post = $this->input->post();
            $data['user_id'] = $this->uid;
            $data['dress_uname'] = $post['dress_uname'];
            $data['dress_utel'] = $post['dress_utel'];
            $data['dress_province'] =$post['province'];
            $data['dress_city'] = $post['city'];
            $data['dress_district'] = $post['district'];
            $data['dress_udress'] = $post['address'];
            $data['dress_add_time'] = time();
            $data['dress_type'] = 1;
            $data1['dress_type']=0;
            $this->member_m->change_dress_by_user_id($this->uid,$data1);
            $this->member_m->add_dress($data);
            echo json_encode(['code' => 200, 'msg' => '新增地址成功']);exit();
        }
        // 地址
        $this->load->model('areas_m');
        $dress=$this->member_m->get_address_by_uid($this->uid);
        if(!empty($dress)){
            foreach($dress as $key=>$val){
                $area =  $this->areas_m->get_area_by_id($val['dress_province']);
                $area2 =  $this->areas_m->get_area_by_id($val['dress_city']);
                $area3 =  $this->areas_m->get_area_by_id($val['dress_district']);
                $dress[$key]['dress_city'] = $area['area_name'].$area2['area_name'].$area3['area_name'];
            }
        }
        $data['dress'] = $dress;
        // 获取所有的省
        $province = $this->areas_m->get_sons_by_pid();
        $data['province']=$province;
        $this->load->view('user_address', $data);
    }

    public function user_loan($page=1){
        $uid = $this->session->userdata('user_id');
        $member = $this->user_m->get_user_by_user_id($uid);
        $limit = 30;
        $this->load->library('pagination');
        $config['uri_segment'] = 4;
        $config['use_page_numbers'] = TRUE;
        $config['base_url'] = site_url('manage/member/xiaoshoudai/'.$uid);
        $config['total_rows'] = $this->db->where("user_id",$uid)->count_all('user_money_sale');
        $config['per_page'] = $limit;
        $config['num_links'] = 10;
        $this->pagination->initialize($config);
        $start = ($page-1)*$limit;
        $data['pagination'] = $this->pagination->create_links();
        $logs = $this->moneysale_m->get_all_user_money_sale($start,$limit,$uid);
        if(!empty($logs)){
            foreach ($logs as $key => $val){
                $orders = $this->order_m->get_shop_orders_by_order_no($val['order_no']);
                $logs[$key]['order_id'] = $orders['order_id'];
            }
        }
        $data['logs'] = $logs;
        $data['member'] = $member;
//        pp($data);exit();
        $this->load->view('user_loan',$data);

    }

    public function verified()
    {

        if($_POST){
            $str['user_uname'] = $this->input->post('user_uname');
            $str['user_card'] = $this->input->post('user_card');
            $str['user_card_rz'] = 1;
            $str['user_card_time'] = time();
            $result = $this->user_m->update_user($this->uid,$str);
            if($result){
                echo json_encode(['status'=>1,"info"=>"认证资料提交成功"]);exit();
            }else{
                echo json_encode(['status'=>2,"info"=>"失败，请稍后再试"]);exit();
            }
        }
        $this->load->view('verified');
    }

    public function user_loan_bill($page = 1){

        $uid = $this->session->userdata('user_id');
	    // 计算月底日期
        $thismonth = date('m');
        $thisyear = date('Y');
        $startDay = $thisyear . '-' . $thismonth . '-1';
        $endDay =  date('t', strtotime($startDay));
        $data['endday'] = $endDay;
        $today = date("d",time());
//        $today = 30;
        if($endDay == $today){
            $data['can_fenqi'] = 1;
        }else{
            $data['can_fenqi'] = 2;
        }
        // 计算当月产生的销售贷
        $beginDate=date('Y-m-01', strtotime(date("Y-m-d")));
        $endDate=date('Y-m-d', strtotime("$beginDate +1 month -1 day"));
        $cur_month_loan = $this->moneysale_m->get_loan_month_by_uid($beginDate,$endDate,$uid);
        if($cur_month_loan == 0){
            $data['can_fenqi'] = 3;
        }
        $data['cur_month_loan'] = $cur_month_loan;
        $uid = $this->session->userdata('user_id');
        $member = $this->user_m->get_user_by_user_id($uid);
        $data['member'] = $member;
        // 查询分期账单
        $limit = 20;
        $this->load->library('pagination');
        $config['uri_segment'] = 4;
        $config['use_page_numbers'] = TRUE;
        $config['base_url'] = site_url('manage/member/xiaoshoudai/'.$uid);
        $config['total_rows'] = $this->db->where("user_id",$uid)->count_all('user_money_sale');
        $config['per_page'] = $limit;
        $config['num_links'] = 10;
        $this->pagination->initialize($config);
        $start = ($page-1)*$limit;
        $data['pagination'] = $this->pagination->create_links();
        $loan_bill = $this->moneystage_m->get_all_user_stage($start,$limit,$uid);
        $data['loan_bil'] = $loan_bill;
        $this->load->view('user_loan_bill',$data);
    }

    public function user_loan_stage(){
        $uid = $this->session->userdata('user_id');
        $member = $this->user_m->get_user_by_user_id($uid);
        $data['member'] = $member;
        // 销售贷月息
        $beginDate=date('Y-m-01', strtotime(date("Y-m-d")));
        $endDate=date('Y-m-d', strtotime("$beginDate +1 month -1 day"));
        $cur_month_loan = $this->moneysale_m->get_loan_month_by_uid($beginDate,$endDate,$uid);
        if($cur_month_loan != 0){
            $cur_month_loan_with_loan_lixi = $cur_month_loan*(1+$this->config->item('loan_lixi'));
            $data['cur_month_loan_with_loan_lixi'] = round($cur_month_loan_with_loan_lixi,2);
            // 默认分三期
            $cur_month_loan_with_loan_three = $cur_month_loan_with_loan_lixi*(1+$this->config->item('loan_three'));
            $data['cur_month_loan_with_loan_three'] = round($cur_month_loan_with_loan_three,2);
            $data['per_cur_month_loan_with_loan_three'] = round($cur_month_loan_with_loan_three/3,2);
            //月底日期
            $thismonth = date('m');
            $thisyear = date('Y');
            $startDay = $thisyear . '-' . $thismonth . '-1';
            $endDay =  date('t', strtotime($startDay));
            $data['endday'] = $endDay;
            $this->load->view('user_loan_stage',$data);
        }else{
            redirect(site_url(V_URL.'user/user_loan_bill'));
        }

    }

    public function get_loan_by_stage(){
        $uid = $this->session->userdata('user_id');
        $stage_num = $this->input->get('stage_num');
        // 获取本月需还款的金额
        $beginDate=date('Y-m-01', strtotime(date("Y-m-d")));
        $endDate=date('Y-m-d', strtotime("$beginDate +1 month -1 day"));
        $cur_month_loan = $this->moneysale_m->get_loan_month_by_uid($beginDate,$endDate,$uid);
        $cur_month_loan_with_loan_lixi = $cur_month_loan*(1+$this->config->item('loan_lixi'));
        $cur_month_loan_with_loan_lixi = round($cur_month_loan_with_loan_lixi,2);
        if($stage_num == 6){
            $cur_month_loan_with_loan = $cur_month_loan_with_loan_lixi*(1+$this->config->item('loan_six'));
        }else if($stage_num == 9){
            $cur_month_loan_with_loan = $cur_month_loan_with_loan_lixi*(1+$this->config->item('loan_nine'));
        }else{
            $cur_month_loan_with_loan = $cur_month_loan_with_loan_lixi*(1+$this->config->item('loan_three'));
        }
        $data['cur_month_loan_with_loan'] = round($cur_month_loan_with_loan,2);
        $data['per_cur_month_loan_with_loan'] = round($cur_month_loan_with_loan/$stage_num,2);
        $html = "";
        $per_cur_month_loan_with_loan = $data['per_cur_month_loan_with_loan'];
        for ($i=0;$i<=$stage_num-1;$i++){
            $back_date=date("Y年m月",strtotime("+$i months",time())).date('t', strtotime(date("Y-m-1",strtotime("+$i months",time()))))."日";
           $html .='<p>'.$back_date.'<em class="per_loan_money">'.$per_cur_month_loan_with_loan.'元</em></p>';
        }
        echo json_encode(['status'=>1,"data"=>$html]);exit();
    }

    public function fenqi_loan(){

        $thismonth = date('m');
        $thisyear = date('Y');
        $startDay = $thisyear . '-' . $thismonth . '-1';
        $endDay =  date('t', strtotime($startDay));
        $data['endday'] = $endDay;
        $today = date("d",time());
//        $today = 30;
        if($endDay != $today){
            echo json_encode(['status'=>2,"info"=>"只能月底才能申请分期"]);exit();
        }
        $uid = $this->session->userdata('user_id');
        $stage_num = $this->input->get('stage_num');
        // 获取本月需还款的金额
        $beginDate=date('Y-m-01', strtotime(date("Y-m-d")));
        $endDate=date('Y-m-d', strtotime("$beginDate +1 month -1 day"));
        $cur_month_loan = $this->moneysale_m->get_loan_month_by_uid($beginDate,$endDate,$uid);
        $cur_month_loan_with_loan_lixi = $cur_month_loan*(1+$this->config->item('loan_lixi'));
        $cur_month_loan_with_loan_lixi = round($cur_month_loan_with_loan_lixi,2);
        if($stage_num == 6){
            $cur_month_loan_with_loan = $cur_month_loan_with_loan_lixi*(1+$this->config->item('loan_six'));
        }else if($stage_num == 9){
            $cur_month_loan_with_loan = $cur_month_loan_with_loan_lixi*(1+$this->config->item('loan_nine'));
        }else{
            $cur_month_loan_with_loan = $cur_month_loan_with_loan_lixi*(1+$this->config->item('loan_three'));
        }
        $cur_month_loan_with_loan = round($cur_month_loan_with_loan,2);
        $per_cur_month_loan_with_loan = round($cur_month_loan_with_loan/$stage_num,2);
        $data = array(
            'user_id'=>$uid,
            "stage_money"=>$cur_month_loan_with_loan,
            "per_stage_money"=>$per_cur_month_loan_with_loan,
            "ctime"=>date("Y-m-d H:i:s",time()),
            'real_stage_money'=>round($cur_month_loan/$stage_num),
            'real_money'=>$cur_month_loan,
        );
        // 计算月底日期
        $stage_id = "";
        $sale_id = "";
        for ($i=0;$i<=$stage_num-1;$i++){
            $data['stage_num']=$i+1;
            $data['back_date']=date("Y-m-",strtotime("+$i months",time())).date('t', strtotime(date("Y-m-1",strtotime("+$i months",time()))));
            $return_id = $this->moneystage_m->add_user_stage($data);
            $stage_id .= $return_id.",";
        }
        $stage_id = substr($stage_id,0,strlen($stage_id)-1);
        if($return_id){
            if(!empty($cur_month_loan)){
                $month_list = $this->moneysale_m->get_loan_month_list_by_uid($beginDate,$endDate,$uid);
                foreach ($month_list as $key=>$value){
                    $this->moneysale_m->sava_user_money_sale($value['id'],['is_return'=>2]);
                    $sale_id .= $value['id'].",";
                }
            }
            $sale_id = substr($sale_id,0,strlen($sale_id)-1);
            // 插入关系表
            $sale_satge_data = array(
                "maney_sale"=>$sale_id,
                "money_stage"=>$stage_id,
            );
            $stage_link_id = $this->moneystage_m->add_sale_satge($sale_satge_data);
            foreach ($month_list as $key=>$value){
                $this->moneysale_m->sava_user_money_sale($value['id'],['stage_link_id'=>$stage_link_id]);
            }
            echo json_encode(['status'=>1,"info"=>"申请分期成功"]);exit();
        }else{
            echo json_encode(['status'=>2,"info"=>"申请分期失败，请稍后再试"]);exit();
        }
    }
}